from rest_framework import serializers
from rbac.models import UserRbacModel,ResourceModel,RoleModel,ResourceMutexModel,ResourceInterface,WorkFlowModel,PositionModel
from rbac.utils.mutex_res import get_mutex_resources

class UserRbacSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserRbacModel
        fields = '__all__'


class ResourceForTransferSerializer(serializers.ModelSerializer):
    key = serializers.IntegerField(source='permission_flag')
    label = serializers.CharField(source='name')
    mutex = serializers.SerializerMethodField()
    disabled = serializers.SerializerMethodField()

    class Meta:
        model = ResourceModel
        fields = ['key', 'label', 'mutex', 'disabled']

    def get_mutex(self, obj):
        return get_mutex_resources(obj.id)

    def get_disabled(self, obj):
        # 父资源的permission_flag为0，将其禁用
        return obj.permission_flag == 0

class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoleModel
        fields = '__all__'

class ResourceSerializer(serializers.ModelSerializer):
    is_parent = serializers.CharField(read_only=True)
    class Meta:
        model = ResourceModel
        fields = '__all__'

class ResourceMutexSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResourceMutexModel
        fields = '__all__'

class ResourceInterfaceSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResourceInterface
        fields = '__all__'


class WorkFlowSerializer(serializers.ModelSerializer):
    class Meta:
        model = WorkFlowModel
        fields = ['id', 'name', 'params', 'status']





class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PositionModel
        fields = ['id', 'name']

